
package andre.grids.db;

import andre.grids.db.exceptions.DbDuplicatedEntry;
import com.db4o.*;

import andre.grids.db.dataclasses.*;
import java.util.*;

/**
 *
 * @author andre
 */
public abstract class DbQueries<T> {
    
    private Database db;
    
    protected DbQueries() {
        db = Database.getGridFsDb();
    }

    public Database getDb() {
        return db;
    }
    
    protected void setDb(Database db)
    {
        this.db = db;
    }
    
    protected Object getSingleObjectByPrototype(Object proto, boolean allowsDuplication) throws DbDuplicatedEntry
    {
        ObjectSet res =getDb().getObjects().get(proto);
        if (res == null)
            return null;
        if (res.size() > 1 && !allowsDuplication)
        {
            throw new DbDuplicatedEntry(proto);
        }
        if (!res.hasNext())
            return null;
        return res.next();        
    }
    
    protected ObjectSet<T> getObjectListByPrototype(T proto)
    {
        ObjectSet<T> set = getDb().getObjects().get(proto);
        return set;
    }
    
    protected T[] objectSetToArray(ObjectSet<T> origin) {
        T[] result = (T[])(new Object[origin.size()]);
        Iterator<T> it = origin.iterator();
        int x = 0;
        for(;it.hasNext();)
            result[x++] = it.next();
        return result;
    }
}
